import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:life_milestones/MS-global-url.dart';
import 'package:life_milestones/MS-request.dart';
import 'package:life_milestones/controller/MS-global-user-controller.dart';
import 'package:life_milestones/util/MS-toast-util.dart';
import 'dart:math';
import 'package:provider/provider.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import '../MS-Model/MS-product-model.dart';
import '../util/MS-log-util.dart';

class MSStorePage extends StatefulWidget {
  const MSStorePage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _MSStorePageState();
  }
}

class _MSStorePageState extends State<MSStorePage> {
  List<MSProduct> products = [];
  final InAppPurchase _inAppPurchase = InAppPurchase.instance;
  late StreamSubscription<List<PurchaseDetails>> _subscription;
  String? orderNo;
  @override
  void initState() {
    super.initState();
    MSRequest().post(MSGlobalUrl.productList, data: {
      "isIncludeSubscription": "false",
      "payChannel": "IAP"
    }).then((value) {
      if (value["code"] == 0 && value["data"] != null) {
        setState(() {
          products = (value["data"] as List).map((e) {
            return MSProduct.fromJson(e);
          }).toList();
        });
      }
    });
    final Stream<List<PurchaseDetails>> purchaseUpdated =
        _inAppPurchase.purchaseStream;
    _subscription =
        purchaseUpdated.listen(_listenToPurchaseUpdated, onDone: () {
      _subscription.cancel();
    }, onError: (e) {
      _subscription.cancel();
    });
    MSLog.addEvent(page: MSLogPages.Store);
    _inAppPurchase.restorePurchases().then((value) {
    });
  }

  buy(String id) async {
    Set<String> kIds = <String>{id};
    final ProductDetailsResponse response =
        await _inAppPurchase.queryProductDetails(kIds);
    if (response.notFoundIDs.isNotEmpty) {
      return;
    }
    List<ProductDetails> products = response.productDetails;
    final ProductDetails productDetails = products.first;
    final PurchaseParam purchaseParam =
        PurchaseParam(productDetails: productDetails);
    _inAppPurchase.buyConsumable(purchaseParam: purchaseParam);
  }

  void _listenToPurchaseUpdated(List<PurchaseDetails> purchaseDetails) async {
    (purchaseDetails).forEach((purchaseDetail) async {
      if (purchaseDetail.status == PurchaseStatus.pending) {
        showLoading();
      } else {
        if (purchaseDetail.status == PurchaseStatus.canceled) {
          await _inAppPurchase.completePurchase(purchaseDetail);
          hideLoading();
        } else if (purchaseDetail.status == PurchaseStatus.error) {
          await _inAppPurchase.completePurchase(purchaseDetail);
          hideLoading();
        } else if (purchaseDetail.status == PurchaseStatus.purchased ||
            purchaseDetail.status == PurchaseStatus.restored) {
          try {
            Map<String, String> headers = MSRequest().getHeader();
            headers['sys_lan'] = MSGlobalUserController().lang ?? "";
            headers['lang'] = MSGlobalUserController().lang ?? "";
            headers['Authorization'] =
                "Bearer${MSGlobalUserController().token}";
            var response = await http.post(
                Uri.parse(MSGlobalUrl.host + MSGlobalUrl.verifyOrder),
                headers: headers,
                body: jsonEncode({
                  "orderNo": orderNo,
                  "payload":
                  purchaseDetail.verificationData.serverVerificationData,
                  "transactionId": purchaseDetail.purchaseID,
                  "type": "1"
                }));
            if (response.statusCode == 200 && jsonDecode(response.body)["code"] == 0) {
              MSGlobalUserController().refreshUserInfo();
            }
          } catch (e) {

          }
          await _inAppPurchase.completePurchase(purchaseDetail);

          hideLoading();
        }
        if (purchaseDetail.pendingCompletePurchase) {

          await _inAppPurchase.completePurchase(purchaseDetail);
        }
      }
    });
  }

  createOrder(String goodsCode) async {
    MSRequest().post(MSGlobalUrl.createOrder, data: {
      "entry": "",
      "source": "",
      "goodsCode": goodsCode,
      "payChannel": "IAP"
    }).then((value) {
      if (value["code"] == 0 && value["data"] != null) {
        orderNo = value["data"]["orderNo"];
        buy(goodsCode);
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<MSGlobalUserController>(builder:
        (BuildContext context, MSGlobalUserController controller, Widget? c) {
      return Scaffold(
        body: SizedBox.expand(
          child: DecoratedBox(
            decoration: const BoxDecoration(
                image:
                    DecorationImage(image: AssetImage("images/store-bg.png"))),
            child: Column(
              children: [
                Container(
                  height: ScreenUtil().statusBarHeight + 57.w,
                  width: double.infinity,
                  padding: EdgeInsets.only(
                      top: ScreenUtil().statusBarHeight,
                      left: 24.w,
                      right: 24.w),
                  child: Stack(
                    children: [
                      Align(
                        alignment: Alignment.centerLeft,
                        child: InkWell(
                          onTap: () {
                            Navigator.of(context).pop();
                          },
                          child: Image.asset(
                            "images/back.png",
                            width: 25.w,
                            fit: BoxFit.fitWidth,
                          ),
                        ),
                      ),
                      Align(
                        alignment: Alignment.center,
                        child: Text(
                          "Coins Shop",
                          style: TextStyle(
                              fontSize: 20.sp,
                              color: const Color(0xFF333333),
                              fontWeight: FontWeight.w500),
                        ),
                      )
                    ],
                  ),
                ),
                Padding(
                  padding:
                      EdgeInsets.only(top: 0.w),
                  child: DecoratedBox(
                    decoration: const BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage("images/store-header-bg.png"))),
                    child: SizedBox(
                      width: double.infinity,
                      height: 92.w,
                      child: Stack(
                        children: [
                          Positioned(
                            top: 8.w,
                            left: 87.w,
                            child: Image.asset(
                              "images/store-coin.png",
                              width: 57.w,
                              fit: BoxFit.fitWidth,
                            ),
                          ),
                          Positioned(
                              left: 200.w,
                              top: 9.w,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  Text(
                                    "My Coins",
                                    style: TextStyle(
                                        fontSize: 12.sp,
                                        height: 1.5,
                                        color: Color(0xFF333333),
                                        fontWeight: FontWeight.w500),
                                  ),
                                  Text(
                                    "${controller.user?.availableCoins ?? 0}",
                                    style: TextStyle(
                                        fontSize: 25.sp,
                                        height: 1.1,
                                        color: Color(0xFF333333),
                                        fontWeight: FontWeight.w900),
                                  ),
                                ],
                              ))
                        ],
                      ),
                    ),
                  ),
                ),
                Expanded(
                    child: Padding(
                  padding: EdgeInsets.only(top: 10.w),
                  child: CustomScrollView(
                    slivers: [
                      SliverPadding(
                        padding: EdgeInsets.symmetric(horizontal: 24.w),
                        sliver: SliverGrid(
                          gridDelegate:
                              SliverGridDelegateWithMaxCrossAxisExtent(
                            maxCrossAxisExtent: 102.w,
                            mainAxisSpacing: 11.w,
                            crossAxisSpacing: 11.w,
                            childAspectRatio: 102 / 140,
                          ),
                          delegate: SliverChildBuilderDelegate(
                            (BuildContext context, int index) {
                              var product = products[index];
                              return InkWell(
                                onTap: () {
                                  createOrder(product.code);
                                },
                                child: Container(
                                  width: 102.w,
                                  height: 140.w,
                                  decoration: const BoxDecoration(
                                      image: DecorationImage(
                                          image: AssetImage(
                                              "images/store-card-bg.png"))),
                                  child: Stack(
                                    children: [
                                      if (product.discount != null &&
                                          product.discount! > 0)
                                        Positioned(
                                            top: 0,
                                            right: 0,
                                            child: Image.asset(
                                              "images/store-discount.jpg",
                                              width: 45.w,
                                              fit: BoxFit.fitWidth,
                                            )),
                                      if (product.discount != null &&
                                          product.discount! > 0)
                                        Positioned(
                                          top: 10.w,
                                          right: 0,
                                          child: Transform.rotate(
                                            angle: pi / 4,
                                            child: Text(
                                              "${product.discount! * 100}% off",
                                              style: TextStyle(
                                                  fontSize: 6.w,
                                                  fontWeight: FontWeight.w600,
                                                  color: Colors.white),
                                            ),
                                          ),
                                        ),
                                      Positioned.fill(
                                          child: Column(
                                        children: [
                                          Padding(
                                            padding: EdgeInsets.only(top: 18.w),
                                            child: Image.asset(
                                              "images/store-coin.png",
                                              width: 40.w,
                                              height: 38.w,
                                            ),
                                          ),
                                          Text(
                                            product.exchangeCoin.toString(),
                                            style: TextStyle(
                                                fontSize: 20.sp,
                                                fontWeight: FontWeight.w600,
                                                color: const Color(0xFF333333)),
                                          ),
                                          Text(
                                            "\$${product.originalPrice}",
                                            style: TextStyle(
                                                fontSize: 10.sp,
                                                fontWeight: FontWeight.w600,
                                                color: const Color(0xFFCECECE)),
                                          ),
                                          const Expanded(child: SizedBox()),
                                          Padding(
                                            padding: EdgeInsets.only(
                                                bottom: 10.w,
                                                left: 5.w,
                                                right: 5.w),
                                            child: Container(
                                              height: 23.w,
                                              width: double.infinity,
                                              decoration: BoxDecoration(
                                                  gradient:
                                                      const LinearGradient(
                                                          colors: [
                                                        Color(0xFFF66C67),
                                                        Color(0xFFF95860)
                                                      ]),
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          11.5.w)),
                                              alignment: Alignment.center,
                                              child: Text(
                                                "\$${product.price}",
                                                style: TextStyle(
                                                    fontSize: 14.sp,
                                                    color: Colors.white,
                                                    fontWeight:
                                                        FontWeight.w600),
                                              ),
                                            ),
                                          )
                                        ],
                                      )),
                                      if (product.isPromotion)
                                        Positioned(
                                            top: 3.w,
                                            left: 4.w,
                                            child: Container(
                                              width: 40.w,
                                              height: 15.w,
                                              decoration: BoxDecoration(
                                                  color: Color(0xFF000000),
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          10.w)),
                                              child: Row(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.center,
                                                children: [
                                                  Image.asset(
                                                    "images/store-hot.png",
                                                    width: 8.w,
                                                    fit: BoxFit.fitWidth,
                                                  ),
                                                  Divider(
                                                    height: 2.w,
                                                    color: Colors.transparent,
                                                  ),
                                                  Text(
                                                    "HOT",
                                                    style: TextStyle(
                                                        fontSize: 9.w,
                                                        fontWeight:
                                                            FontWeight.w900,
                                                        color: Colors.white),
                                                  )
                                                ],
                                              ),
                                            )),
                                      if (product.tags != null &&
                                          product.tags!.isNotEmpty)
                                        Positioned(
                                          top: 3.w,
                                          left: 4.w,
                                          child: Container(
                                            padding: EdgeInsets.symmetric(
                                                horizontal: 7.w, vertical: 3.w),
                                            decoration: BoxDecoration(
                                                color: const Color(0xFF148857),
                                                borderRadius:
                                                    BorderRadius.circular(
                                                        16.5.w)),
                                            child: Text(
                                              product.tags!,
                                              style: TextStyle(
                                                  fontSize: 9.sp,
                                                  color: Colors.white,
                                                  fontWeight: FontWeight.w500),
                                            ),
                                          ),
                                        )
                                    ],
                                  ),
                                ),
                              );
                            },
                            childCount: products.length,
                          ),
                        ),
                      ),
                      SliverPadding(
                        padding:
                            EdgeInsets.only(top: 50.w, left: 5.w, right: 5.w),
                        sliver: SliverToBoxAdapter(
                          child: Text(
                            "By submitting this order, you consent that you agree to the\"Terms of Service\" and \"Privacy Policy\""
                                .toUpperCase(),
                            style: TextStyle(
                                fontSize: 10.sp,
                                height: 1.6,
                                fontWeight: FontWeight.w500,
                                color: const Color(0xFF333333)),
                            textAlign: TextAlign.center,
                          ),
                        ),
                      )
                    ],
                  ),
                ))
              ],
            ),
          ),
        ),
      );
    });
  }
}
